<template>
  <div class="table" style="padding:20px">
    <div style="overflow: auto; height: 850px">
      <div style="padding-block-end: 10px">
        <el-input id="task_name" v-model="task_page.task_name" placeholder="请输入任务名称" style="width: 800px; padding-right: 10px;" />
        <el-button type="primary" @click="task_all">搜索</el-button>
        <el-button style="float: right" type="success" @click="add_new_task">新增任务</el-button>
      </div>
      <div>
        <el-table
          :data="table_data"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          style="float:left;width:100%"
        >
          <el-table-column align="center" label="ID" width="80px">
            <template slot-scope="scope">
              {{ scope.row.task_id }}
            </template>
          </el-table-column>
          <el-table-column label="任务名称" width="200px">
            <template slot-scope="scope">
              {{ scope.row.task_name }}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="类型" align="center" width="110px">
            <template slot-scope="scope">
              <span v-if="scope.row.run_type===1"><el-tag type="primary">接口自动化</el-tag></span>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="状态" align="center" width="80px">
            <template slot-scope="scope">
              <span v-if="scope.row.status===1"><el-tag type="success">开启</el-tag></span>
              <span v-if="scope.row.status!==1"><el-tag type="danger">关闭</el-tag></span>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="周期" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.task_type === 1"><el-tag type="primary" plain>单次执行</el-tag></span>
              <span v-if="scope.row.task_type === 2"><el-tag type="success" plain>间隔执行</el-tag></span>
              <span v-if="scope.row.task_type === 3"><el-tag type="warning" plain>周期执行</el-tag></span>
            </template>
          </el-table-column>
          <el-table-column label="任务描述" align="center" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.task_description }}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.active===1"><el-tag type="info">未执行</el-tag></span>
              <span v-if="scope.row.active===2"><el-tag type="primary">等待执行中</el-tag></span>
              <span v-if="scope.row.active===3"><el-tag type="success">执行完成</el-tag></span>
            </template>
          </el-table-column>
          <el-table-column label="username" align="center">
            <template slot-scope="scope">
              {{ scope.row.username }}
            </template>
          </el-table-column>
          <el-table-column align="left" prop="update_time" label="update_time">
            <template slot-scope="scope">
              <span>{{ scope.row.update_time }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="create_time" label="create_time">
            <template slot-scope="scope">
              <span>{{ scope.row.create_time }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="action" label="操作" width="250px">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="get_task_info(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="del(scope.row.task_id)">删除</el-button>
              <el-button v-if="scope.row.run_type===1" type="success" size="small" @click="result_view(scope.row.task_id)">查看结果</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="block">
        <el-pagination
          background
          :current-page="task_page.current_page"
          :page-sizes="[10, 20, 50]"
          :page-size="task_page.size_page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="case_total"
          style="float: left; padding: 10px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div>
      <el-dialog
        title="定时任务"
        :visible.sync="add_dialog"
        width="50%"
      >
        <el-form ref="form" :model="add_form" label-width="100px">
          <el-form-item label="任务名称：">
            <el-input v-model="add_form.task_name" />
          </el-form-item>
          <el-form-item label="任务类型：">
            <el-radio-group v-model="add_form.task_type">
              <el-radio label="1">单次执行</el-radio>
              <el-radio label="2">间隔执行</el-radio>
              <el-radio label="3">周期执行</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="add_form.task_type==='1'" label="任务时间：" prop="task_time">
            <el-date-picker
              v-model="add_form.task_time"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间："
              default-time="00:00:00"
            />
          </el-form-item>
          <el-form-item v-if="add_form.task_type==='2'" label="间隔时间：" prop="task_hour">
            <el-input-number v-model="add_form.task_hour" :precision="0" :min="1" :max="6000" label="正整数" />
            （分钟）
          </el-form-item>
          <el-form-item v-if="add_form.task_type==='3'" label="执行周期：">
            <el-select v-model="add_form.task_week_days" clearable placeholder="请选择日期" style="padding-right: 10px">
              <el-option
                v-for="item in week"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-time-select
              v-model="add_form.task_week_times"
              value-format="hh:mm"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
              placeholder="任意时间点："
            />
          </el-form-item>
          <el-form-item label="任务状态：">
            <el-switch
              v-model="add_form.task_status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="开启"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="钉钉推送：">
            <el-input v-model="add_form.ding_talk" />
          </el-form-item>
          <el-form-item label="任务描述：">
            <el-input v-model="add_form.task_description" type="textarea" />
          </el-form-item>
          <el-form-item label="执行类型：">
            <el-radio-group v-model="add_form.run_type">
              <el-radio label="1">接口自动化</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="add_form.run_type === '1'">
            <el-form-item label="接口集：">
              <el-cascader
                ref="value_cascade"
                style="width: 250px"
                placeholder="输入接口名称搜索"
                :options="api_tree"
                :props="{value:'id',label:'label',emitPath:false, multiple: true}"
                filterable
                clearable
                :collapse-tags="true"
                :show-all-levels="false"
                @change="getChecked"
              >
                <span slot-scope="{ node, data }" class="custom-tree-node">
                  <span v-if="data.type===0"><i :class="icon0" style="padding-right: 7px" />{{ node.label }}{{ "("+node.value+")" }}</span>
                  <span v-if="data.type===1"><i :class="icon1" style="padding-right: 7px" />{{ node.label }}{{ "("+node.value+")" }}</span>
                  <span v-if="data.type===2"><i :class="icon2" style="padding-right: 7px" />{{ node.label }}{{ "("+node.value+")" }}</span>
                </span>
              </el-cascader>
            </el-form-item>
            <el-form-item>
              <el-table
                :data="api_list"
                element-loading-text="Loading"
                border
                fit
                highlight-current-row
                style="width:100%"
              >
                <el-table-column align="center" label="ID">
                  <template slot-scope="scope">
                    {{ scope.row.id }}
                  </template>
                </el-table-column>
                <el-table-column align="center" label="接口名称">
                  <template slot-scope="scope">
                    {{ scope.row.label }}
                  </template>
                </el-table-column>
                <el-table-column align="center" label="执行步骤">
                  <template slot-scope="scope">
                    <el-form-item :rules="step_rule.step">
                      <el-input-number v-model="scope.row.step" :min="1" controls-position="right" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作列">
                  <template slot-scope="scope">
                    <el-button type="danger" size="small" @click="del_api(scope.$index, scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
          <el-form-item>
            <div v-show="1 === number">
              <el-button v-if="add_form.run_type === '1'" type="primary" style="float: right" @click="add_task">立即创建</el-button>
            </div>
            <div v-show="2 === number">
              <el-button v-if="add_form.run_type === '1'" type="primary" style="float: right" @click="edit_task">保存</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div>
      <el-dialog
        title="任务结果"
        :visible.sync="result_dialog"
        width="70%"
      >
        <el-table
          :data="result_data"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
        >
          <el-table-column align="center" label="任务来源">
            <template slot-scope="scope">
              {{ scope.row.from_task }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="ID" width="90px">
            <template slot-scope="scope">
              {{ scope.row.case_id }}
            </template>
          </el-table-column>
          <el-table-column label="接口名称">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.task_status===1"><el-tag type="success">成功</el-tag></span>
              <span v-if="scope.row.task_status!==1"><el-tag type="danger">失败</el-tag></span>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="请求方法" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.method===1"><el-tag type="success">GET</el-tag></span>
              <span v-if="scope.row.method===2"><el-tag type="danger">POST</el-tag></span>
              <span v-if="scope.row.method===3"><el-tag type="info">PUT</el-tag></span>
              <span v-if="scope.row.method===4"><el-tag type="warning">DELETE</el-tag></span>
            </template>
          </el-table-column>
          <el-table-column label="url" align="center">
            <template slot-scope="scope">
              {{ scope.row.url }}
            </template>
          </el-table-column>
          <el-table-column label="接口响应时间" align="center">
            <template slot-scope="scope">
              {{ scope.row.api_runtime }}
            </template>
          </el-table-column>
          <el-table-column label="任务执行时间" align="center">
            <template slot-scope="scope">
              {{ scope.row.task_runtime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="success" size="small" @click="result_info(scope.row.case_id)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
    <div>
      <el-dialog
        title="任务结果详情"
        :visible.sync="result_details_dialog"
        width="50%"
      >
        <el-tabs v-model="tabs_activeName">
          <el-tab-pane label="请求url" name="req_url">
            <p>{{ result_details.req_url }}</p>
          </el-tab-pane>
          <el-tab-pane label="请求params" name="params">
            <json-viewer :value="result_details.params" />
          </el-tab-pane>
          <el-tab-pane label="请求headers" name="headers">
            <json-viewer :value="result_details.headers" />
          </el-tab-pane>
          <el-tab-pane label="请求Body" name="Body">
            <json-viewer :value="result_details.body" />
          </el-tab-pane>
          <el-tab-pane label="请求结果" name="req_result">
            <json-viewer :value="result_details.req_result" />
          </el-tab-pane>
          <el-tab-pane label="断言结果" name="assert_data">
            <json-viewer :value="result_details.assert_data" />
          </el-tab-pane>
          <el-tab-pane label="参数提取" name="extract_result">
            <json-viewer :value="result_details.extract_result" />
          </el-tab-pane>
          <el-tab-pane label="接口响应时间" name="res_runtime">
            <p>接口响应时间： {{ result_details.res_runtime }}</p>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
    <div>
      <el-dialog
        title="提示"
        :visible.sync="del_task_dialog"
        width="30%"
      >
        <span>删除任务后，定时任务也随之删除</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="del_task_dialog = false">取 消</el-button>
          <el-button type="primary" @click="del_task()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  add_single_task,
  delete_task,
  edit_sigle_task,
  get_single_task,
  get_task,
  get_task_result,
  get_task_result_details
} from "@/api/task";
import { getCase_tree } from "@/api/testcase";

export default {
  name: "TaskList",
  components: {
  },
  data() {
    return {
      devices: [],
      step_rule: {
        step: [{
          required: true,
          message: '请输入',
          trigger: 'change'
        }]
      },
      del_task_dialog: false,
      del_id: null,
      tabs_activeName: "req_url",
      update_task: true,
      number: null,
      icon0: 'el-icon-s-home',
      icon1: 'el-icon-folder-opened',
      icon2: 'el-icon-document',
      case_total: 0,
      task_page: {
        task_name: "",
        current_page: 1,
        size_page: 10,
      },
      table_data: [],
      task_form: {
        task_id: null
      },
      task_name: '',
      date_time: "",
      result_details_dialog: false,
      result_form: {
        task_id: null,
        case_id: null
      },
      result_details: [],
      result_dialog: false,
      result_data: [],
      choice_api: false,
      add_dialog: false,
      task_cases: [
        {
          menu_id: null,
          step: null,
        }
      ],
      devices_list: [],
      add_form: {
        task_name: "",
        task_description: "",
        task_time: "",
        task_hour: "",
        task_week_days: "",
        task_week_times: "",
        task_type: '1',
        ding_talk: "",
        run_type: 1
      },
      req_form: {
        task_name: "",
        task_description: "",
        task_time: "",
        task_hour: "",
        task_week_days: "",
        task_week_times: "",
        task_type: '1',
        task_cases: [
          {
            menu_id: null,
            step: null,
          }
        ]
      },
      radio: null,
      api_tree: [],
      week: [{ label: "周一", value: "mon" }, { label: "周二", value: "tue" }, { label: "周三", value: "wed" },
        { label: "周四", value: "thu" }, { label: "周五", value: "fri" }, { label: "周六", value: "sat" }, { label: "周日", value: "sun" },
        { label: "每天", value: "0-6" }
      ],
      api_list: [],
      app_tree: [],
      app_list: []
    }
  },
  created() {
    this.task_all()
    this.is_login()
  },
  methods: {
    is_login() {
      // eslint-disable-next-line no-prototype-builtins
      if (localStorage.hasOwnProperty("token") === false || localStorage.getItem("token") === '' || localStorage.getItem("token") === null || localStorage.getItem("user_id") === '') {
        this.$router.push("/login")
        this.$message.error("未登录，请前往登录")
      }
    },
    del_api(index, row) {
      this.api_list.splice(index, 1)
    },
    getChecked() {
      const result = []
      const list = this.$refs["value_cascade"].getCheckedNodes()
      list.forEach(item => {
        if (item.data.type === 2) {
          result.push({ "id": item.value, "step": item.step, "label": item.label, "type": item.type })
        }
      })
      this.api_list = result
    },
    getNowTime() {
      let now = ""
      const yy = new Date().getFullYear()
      const mm = new Date().getMonth() + 1
      const dd = new Date().getDate()
      const hh = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
      const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds()
        : new Date().getSeconds()
      now = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
      return now
    },
    // 页签-条/页 跳转
    handleSizeChange(val) {
      this.task_page.size_page = val
      this.task_all()
    },
    // 底部页签跳转
    handleCurrentChange(val) {
      this.task_page.current_page = val
      this.task_all()
    },
    task_all() {
      get_task(this.task_page).then(res => {
        this.table_data = res.data.content
        this.case_total = res.data.case_total
        this.task_page.current_page = res.data.current_page
        this.task_page.size_page = res.data.size_page
      })
    },
    // 新增任务窗口
    add_new_task() {
      this.api_list = []
      this.get_tree()
      this.add_form = {
        task_name: "", task_status: 0, task_description: "", task_time: "",
        task_hour: "", task_type: '1', task_week_times: "", task_week_days: "", ding_talk: "", run_type: '1',
        devices: ""
      }
      this.task_cases = [{ menu_id: null, step: null }]
      this.add_dialog = true
      this.number = 1
    },
    add_task() {
      const list = []
      this.api_list.forEach(item => {
        list.push({ "id": item.id, "step": item.step, "label": item.label })
      })
      const req = this.req_form
      req.task_name = this.add_form.task_name
      req.task_status = this.add_form.task_status
      req.ding_talk = this.add_form.ding_talk
      req.task_cases = list
      req.run_type = Number(this.add_form.run_type)
      req.task_hour = this.add_form.task_hour
      req.task_week_days = this.add_form.task_week_days
      req.task_week_times = this.add_form.task_week_times
      req.task_type = Number(this.add_form.task_type)
      req.task_description = this.add_form.task_description
      req.task_time = this.add_form.task_time
      req.user_id = Number(localStorage.getItem("user_id"))
      if (req.task_type === 1) {
        if (Date.parse(req.task_time) <= Date.parse(this.getNowTime())) {
          this.$message.error("执行时间必须大于当前时间")
        } else {
          add_single_task(this.req_form).then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.add_dialog = false
              this.task_all()
            } else if (res.data.code === 1001) {
              this.$message.error(res.data.message)
              this.$router.push("/login")
            } else {
              this.$message.error(res.data.message)
            }
          })
        }
      } else {
        add_single_task(this.req_form).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.add_dialog = false
            this.task_all()
          } else if (res.data.code !== 200) {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    // 获取接口
    get_tree() {
      getCase_tree().then(res => {
        this.api_tree = res.data.content
      })
    },
    // 获取单个任务信息
    get_task_info(task) {
      this.get_tree()
      this.number = 2
      this.add_dialog = true
      this.task_form.task_id = task.task_id
      get_single_task(this.task_form).then(res => {
        this.add_form = res.data.content[0]
        this.add_form.run_type = String(res.data.content[0].run_type)
        this.api_list = res.data.content[0].task_cases
        this.app_list = res.data.content[0].task_cases
      })
    },
    del(task_id) {
      this.del_task_dialog = true
      this.del_id = task_id
    },
    // 删除任务
    del_task() {
      this.task_form.task_id = this.del_id
      delete_task(this.task_form).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.del_task_dialog = false
          this.task_all()
        } else if (res.data.code === 100) {
          this.$message.error(res.data.message)
        }
      })
    },
    // 查看结果
    result_view(task_id) {
      this.result_dialog = true
      this.task_form.task_id = task_id
      get_task_result(this.task_form).then(res => {
        if (res.data.code === 200) {
          this.result_data = res.data.content
        } else if (res.data.code === 100) {
          this.$message.error(res.data.message)
        }
      })
    },
    // 查看详细结果
    result_info(case_id) {
      this.result_details_dialog = true
      const req = this.result_form
      req.task_id = this.task_form.task_id
      req.case_id = case_id
      get_task_result_details(this.result_form).then(res => {
        if (res.data.code === 200) {
          this.result_details = res.data.content[0]
          const result = res.data.content[0]
          this.result_details.header = result.header
          this.result_details.body = result.body
          this.result_details.params = result.params
          this.result_details.extract_result = result.extract_result
          this.result_details.assert_data = result.assert_data
        } else if (res.data.code !== 200) {
          this.$message.error(res.data.message)
        }
      })
    },
    // 编辑接口自动化任务
    edit_task() {
      const list = []
      this.api_list.forEach(item => {
        list.push({ "id": item.id, "step": item.step, "label": item.label })
      })
      const req = this.req_form
      req.task_id = this.task_form.task_id
      req.task_name = this.add_form.task_name
      req.task_status = this.add_form.task_status
      req.ding_talk = this.add_form.ding_talk
      req.task_cases = list
      req.task_hour = this.add_form.task_hour
      req.run_type = Number(this.add_form.run_type)
      req.task_week_days = this.add_form.task_week_days
      req.task_week_times = this.add_form.task_week_times
      req.task_type = Number(this.add_form.task_type)
      req.task_description = this.add_form.task_description
      req.task_time = this.add_form.task_time
      req.user_id = Number(localStorage.getItem("user_id"))
      if (req.task_time !== "") {
        if (Date.parse(req.task_time) <= Date.parse(this.getNowTime())) {
          this.$message.error("执行时间必须大于当前时间")
        } else {
          edit_sigle_task(this.req_form).then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.add_dialog = false
              this.task_all()
            } else if (res.data.code === 100 && res.data.Exception === 'Scheduler is already running') {
              this.$message.success("任务编辑成功")
              this.add_dialog = false
            } else {
              this.$message.success(res.data.message)
            }
          })
        }
      } else {
        edit_sigle_task(this.req_form).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.add_dialog = false
            this.task_all()
          } else if (res.data.code === 100) {
            this.$message.error(res.data.message)
          }
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.el-dialog__body{
  height: 100%;
}
</style>
